package com.djk.daily.thread.stopthreads;

/**
 * @author dujunkai
 * @version 1.0
 * @description: 两个线程交替打印0~100的奇偶数，用synchronized关键字实现
 * @date 2021/7/5 16:24
 */
public class WaitNotifyPrintOddEvenSyn {
    private static final Object object = new Object();
    private static int count;

    public static void main(String[] args) throws InterruptedException {
        Thread threadOdd = new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    synchronized (object) {
                        if ((count & 1) == 0) {
                            System.out.println(Thread.currentThread().getName() + count++);
                        }
                    }
                }
            }
        }, "偶数");

        Thread threadEven = new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    synchronized (object) {
                        if ((count & 1) == 1) {
                            System.out.println(Thread.currentThread().getName() + count++);
                        }
                    }
                }
            }
        }, "奇数");

        threadOdd.start();
        Thread.sleep(100);
        threadEven.start();
    }
}
